<template>
    <van-nav-bar title="参与拼团" left-text="" left-arrow @click-left="goBack" />
    <!-- 默认地址 -->
    <van-contact-card type="edit" :tel="address.mobile" :name="address.consignee" @click="toAdressPages"
        v-if="Object.values(address).length > 0" />
    <!-- 添加地址 -->
    <van-contact-card type="add" @click="toAdressPages" v-else />

    <!-- 商品信息 -->
    <van-card  :price="prices" :title="product.name" class="goods-card"
        :thumb="product.thumbs_text" :num="nums">
        <template #desc>
            <div v-if="attrs">
                <van-tag v-for="items in attrs" type="warning" size="medium" style="margin-right: 10px;">{{
                    items.name }}</van-tag>
            </div>
            <div>单价：{{ product.price }}</div>
        </template>
    </van-card>

    <!-- 支付方式 -->
    <van-field v-model="payName" is-link readonly label="支付方式" placeholder="选择支付方式" @click="showPicker = true" />
    <van-popup v-model:show="showPicker" round position="bottom">
        <van-picker :columns="columns" @cancel="showPicker = false" @confirm="onPayConfirm" />
    </van-popup>

    <!-- 订单备注 -->
    <van-field v-model="remark" rows="2" autosize label="订单备注" type="textarea" maxlength="120" placeholder="请输入订单备注"
        show-word-limit />

    <!-- 提交订单 -->
    <van-submit-bar :price="total" button-text="确认支付" @submit="onSubmit" />

</template>
<script setup>
const { proxy } = getCurrentInstance()
const goBack = () => { proxy.$router.go(-1) }
const LoginUser = reactive(proxy.$cookies.get('LoginUser') ? proxy.$cookies.get('LoginUser') : {})
const address = ref(proxy.$cookies.get('address') ? proxy.$cookies.get('address') : {})
const proid = proxy.$route.query.proid ? proxy.$route.query.proid : 0
const attrs = ref(proxy.$cookies.get('relationids') ? JSON.parse(proxy.$cookies.get('relationids')) : [])
const nums = ref(proxy.$route.query.nums ?? 0)
const product = ref({})
const payName = ref('')
const pay = ref('')
const showPicker = ref(false)
const prices = ref(0)
const columns = [
    { text: '余额支付', value: 'money' },
    { text: '支付宝', value: 'zfb' },
    { text: '微信支付', value: 'wx' },
];

// 订单备注
const remark = ref('')

onBeforeMount(() => {
    if (Object.values(address.value).length <= 0) {
        getAddressData()
    }
    getProductInfoData()
})

const getAddressData = async () => {
    let result = await Api.addressSelected({
        busid: LoginUser.id
    })

    if (result.code == 1) {
        address.value = result.data
    }
}

const getProductInfoData = async () => {
    let result = await Api.productInfo({
        busid: LoginUser.id,
        proid: proid,
    })

    if (result.code == 1) {
        product.value = result.data.info
    }
}


const toAdressPages = () => {
    proxy.$router.push({
        path: '/business/address/index',
        query: {
            action: 'order'
        }
    })
}

const onPayConfirm = ({ selectedValues, selectedOptions }) => {
    showPicker.value = false;
    payName.value = selectedOptions[0].text
    pay.value = selectedOptions[0].value
}

// 计算总价
const total = computed(() => {
    let num = 0;
    // 商品属性
    if (attrs.value.length > 0) {
        let totals = attrs.value.reduce((accumulator, item) => accumulator + (parseFloat(item.price) / 100), 0,);
        prices.value = parseFloat(product.value.buy) + parseFloat(totals)
        num = (parseFloat(prices.value) * parseInt(nums.value)).toFixed(2);
    } else {
        num = (parseFloat(product.value.buy) * parseInt(nums.value)).toFixed(2);
        prices.value = parseFloat(product.value.buy)
    }
    return num * 100;
})


const onSubmit = async () => {

    let relationids = [];
    // 商品属性
    if(attrs.value.length > 0)
    {
        relationids = attrs.value.map((item) => item.id)
    }

    let data = {
        busid: LoginUser.id,
        addrid: address.value.id,
        total: total.value / 100,
        remark: remark.value,
        pay: pay.value,
        proid: proid,
        attrs: relationids.toString(),
        nums: nums.value
    }

    console.log(attrs.value)

    if (JSON.stringify(address.value) == '{}') {
        error('请选择收货地址');
        return false;
    }

    if (!pay.value) {
        error('请选择支付方式');
        return false;
    }

    let result = await Api.teamJoin(data)
    if (result.code == 1) {
        success({
            message: result.msg,
            onClose: () => {
                proxy.$router.push('/team/index')
            }
        });

    } else {
        error(result.msg);
    }
}

</script>

<style scoped>
/* 组件穿透样式写法 */
:deep(.van-field__control:read-only) {
    text-align: right;
}
</style>